import bus from './/bus';

let websock = null;
let lockReconnect = false;//避免重复连接
let tt;
let timeout = 3 * 1000;//3秒一次心跳
let timeoutObj = null;//心跳心跳倒计时
let serverTimeoutObj = null;//心跳倒计时
let timeoutnum = null;//断开 重连倒计时

function ip() {
    let ip = localStorage.getItem('lastLoginIp');
    if (!ip) {
        ip = localStorage.getItem('lastLoginIp');
        alert('ip地址获取失败！');
        return;
    }
    return ip;
}

function sellerId() {
    let sellerId = localStorage.getItem("userId");
    return sellerId;
}

function initWebSocket() { //初始化weosocket
    //ws地址
    let wsuri;
    const host = window.location.hostname; //主机
    const protocol = window.location.protocol; //协议
    if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
        if (protocol === 'http:') {
            wsuri = "ws://123.207.239.201/carSocket/admin/" + sellerId() + "/" + ip();
        } else {
            wsuri = "wss://123.207.239.201/carSocket/admin/" + sellerId() + "/" + ip();
        }
    } else {
        if (protocol === 'http:') {
            wsuri = "ws://" + host + ":31331/carSocket/admin/" + sellerId() + "/" + ip();
        } else {
            wsuri = "wss://" + host + ":31331/carSocket/admin/" + sellerId() + "/" + ip();
        }
    }
    websock = new WebSocket(wsuri);
    websock.onmessage = function (e) {
        websocketonmessage(e);
    };
    websock.onclose = function (e) {
        websocketclose(e);
    };
    websock.onopen = function () {
        websocketOpen();
    };

    //连接发生错误的回调方法
    websock.onerror = function () {
        console.log("WebSocket连接发生错误");
        reconnect()
    }
}

// 实际调用的方法
function sendSock(agentData) {
    if (websock.readyState === websock.OPEN) {
        //若是ws开启状态
        websocketsend(agentData)
    } else if (websock.readyState === websock.CONNECTING) {
        // 若是 正在开启状态，则等待1s后重新调用
        setTimeout(function () {
            sendSock(agentData);
        }, 1000);
    } else {
        // 若未开启 ，则等待1s后重新调用
        setTimeout(function () {
            sendSock(agentData);
        }, 1000);
    }
}

//数据接收
function websocketonmessage(e) {
    console.log(e.data);
    if (e.data == 1) {
        bus.$emit("msgData", e.data);
        reset()//重置心跳
    }
}

//数据发送
function websocketsend(agentData) {
    websock.send(JSON.stringify(agentData));
}

//关闭
function websocketclose(e) {
    //console.log("没有连接成功 (" + e.code + ")");
    console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    websock.close();
    reconnect()
}

//关闭
function close() {
    websock.close();
}

function websocketOpen(e) {
    console.log("连接成功");
    start()//开启心跳
}

function reconnect() {
    if (lockReconnect) {
        return;
    }
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    tt && clearTimeout(tt);
    tt = setTimeout(function () {
        initWebSocket();
        lockReconnect = false;
    }, 1000);
}

function reset() {//重置心跳
    //清除时间
    clearTimeout(timeoutObj);
    clearTimeout(serverTimeoutObj);
    //重启心跳
    start();
}

function start() {//开启心跳
    timeoutObj && clearTimeout(timeoutObj);
    serverTimeoutObj && clearTimeout(serverTimeoutObj);
    timeoutObj = setTimeout(function () {
        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (websock.readyState == 1) {//如果连接正常
            websock.send("heartCheck");
            start()
        } else {//否则重连
            reconnect();
        }
    }, timeout)
}

// initWebSocket();

export {sendSock, initWebSocket, close}
